package com.mindskip.xzs.controller.admin;


import cn.hutool.poi.excel.ExcelReader;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.configuration.property.SystemConfig;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.service.FileUpload;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.service.UserService;
import com.mindskip.xzs.utility.ErrorUtil;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.viewmodel.admin.file.UeditorConfigVM;
import com.mindskip.xzs.viewmodel.admin.file.UploadResultVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditItemVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionExcelRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@RequestMapping("/api/admin/upload")
@RestController("AdminUploadController")
public class UploadController extends BaseApiController {

    private final FileUpload fileUpload;
    private final SystemConfig systemConfig;
    private final QuestionService questionService;
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    private static final String IMAGE_UPLOAD = "imgUpload";
    private static final String IMAGE_UPLOAD_FILE = "upFile";
    private final UserService userService;
    final String urlLocal = "http://ndjlba.com:9000";

    @Autowired
    public UploadController(FileUpload fileUpload, SystemConfig systemConfig, QuestionService questionService, UserService userService) {
        this.fileUpload = fileUpload;
        this.systemConfig = systemConfig;
        this.questionService = questionService;
        this.userService = userService;
    }

    @ResponseBody
    @RequestMapping("/configAndUpload")
    public Object upload(HttpServletRequest request, HttpServletResponse response) {
        String action = request.getParameter("action");
        if (action.equals(IMAGE_UPLOAD)) {
                MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
                MultipartFile multipartFile = multipartHttpServletRequest.getFile(IMAGE_UPLOAD_FILE);
                long attachSize = multipartFile.getSize();
                String imgName = multipartFile.getOriginalFilename();
                String subffix = imgName.substring(imgName.lastIndexOf(".") + 1, imgName.length());
                String imageType = imgName.substring(imgName.lastIndexOf("."));
                String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                String filePath;
                try {
                    String path = "D:\\media\\image";
                    File file = new File(path);
                    ////文件夹不存在就创建
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    //保存文件
                    try {
                        multipartFile.transferTo(new File(file + "\\" + fileName + "." + subffix));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    filePath = urlLocal + "/" + fileName + "." + subffix;
                    //filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
                    UploadResultVM uploadResultVM = new UploadResultVM();
                    uploadResultVM.setOriginal(imgName);
                    uploadResultVM.setName(imgName);
                    uploadResultVM.setUrl(filePath);
                    uploadResultVM.setSize(attachSize);
                    uploadResultVM.setType(imageType);
                    uploadResultVM.setState("SUCCESS");
                    return uploadResultVM;
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
        } else {
            UeditorConfigVM ueditorConfigVM = new UeditorConfigVM();
            ueditorConfigVM.setImageActionName(IMAGE_UPLOAD);
            ueditorConfigVM.setImageFieldName(IMAGE_UPLOAD_FILE);
            ueditorConfigVM.setImageMaxSize(2048000L);
            ueditorConfigVM.setImageAllowFiles(Arrays.asList(".png", ".jpg", ".jpeg", ".gif", ".bmp"));
            ueditorConfigVM.setImageCompressEnable(true);
            ueditorConfigVM.setImageCompressBorder(1600);
            ueditorConfigVM.setImageInsertAlign("none");
            ueditorConfigVM.setImageUrlPrefix("");
            ueditorConfigVM.setImagePathFormat("");
            return ueditorConfigVM;
        }
        return null;
    }


    @RequestMapping("/image2")
    @ResponseBody
    public RestResponse questionUploadAndReadExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        long attachSize = multipartFile.getSize();
        String imgName = multipartFile.getOriginalFilename();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
            //userService.changePicture(getCurrentUser(), filePath);
            return RestResponse.ok(filePath);
        } catch (IOException e) {
            return RestResponse.fail(2, e.getMessage());
        }
    }

    @RequestMapping("/excel")
    @ResponseBody
    public RestResponse questionUploadAndExcel(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        String fileName = multipartFile.getOriginalFilename() == null || "".equals(multipartFile.getOriginalFilename())
                ? multipartFile.getName() : multipartFile.getOriginalFilename();
        if (null == fileName) {
            return RestResponse.fail(2, "检查文件格式是否正确！");
        }
        if (fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
            try {
                InputStream inputStream = multipartFile.getInputStream();
                ExcelReader reader = cn.hutool.poi.excel.ExcelUtil.getReader(inputStream);
                reader.addHeaderAlias("题型", "questionTypeStr");
                reader.addHeaderAlias("学科", "subject");
                reader.addHeaderAlias("知识点", "gradeLevelStr");
                reader.addHeaderAlias("题干", "title");
                reader.addHeaderAlias("选项A", "contentA");
                reader.addHeaderAlias("选项B", "contentB");
                reader.addHeaderAlias("选项C", "contentC");
                reader.addHeaderAlias("选项D", "contentD");
                reader.addHeaderAlias("选项E", "contentE");
                reader.addHeaderAlias("选项F", "contentF");
                reader.addHeaderAlias("选项G", "contentG");
                reader.addHeaderAlias("选项H", "contentH");
                reader.addHeaderAlias("解析", "analyze");
                reader.addHeaderAlias("分数", "score");
                reader.addHeaderAlias("难度", "difficult");
                reader.addHeaderAlias("答案", "correct");
                List<QuestionExcelRequest> excelQTOList = reader.readAll(QuestionExcelRequest.class);
                for (QuestionExcelRequest excelRequest : excelQTOList) {
                    QuestionEditRequestVM model = new QuestionEditRequestVM();
                    Integer questionType = excelRequest.getQuestionType(excelRequest.getQuestionTypeStr());
                    model.setQuestionType(questionType);
                    model.setAnalyze(null == excelRequest.getAnalyze() ? "题目简单,注意审题和细心" : excelRequest.getAnalyze());
                    model.setCorrect(excelRequest.getCorrect());
                    model.setCorrectArray(Arrays.asList(excelRequest.getCorrect().split(",")));
                    model.setDifficult(null == excelRequest.getDifficult() ? 1 : excelRequest.getDifficult());
                    model.setScore(null == excelRequest.getScore() ? "1" : excelRequest.getScore());
                    model.setTitle(excelRequest.getTitle());
                    model.setSubjectId(excelRequest.getSubjectId(excelRequest.getSubject()));
                    List<QuestionEditItemVM> items = new ArrayList<>();
                    if (StringUtils.isNotEmpty(excelRequest.getContentA())) {
                        QuestionEditItemVM questionEditItemVM = new QuestionEditItemVM();
                        questionEditItemVM.setPrefix("A");
                        questionEditItemVM.setContent(excelRequest.getContentA());
                        items.add(questionEditItemVM);
                    }
                    if (StringUtils.isNotEmpty(excelRequest.getContentB())) {
                        QuestionEditItemVM questionEditItemVM = new QuestionEditItemVM();
                        questionEditItemVM.setPrefix("B");
                        questionEditItemVM.setContent(excelRequest.getContentB());
                        items.add(questionEditItemVM);
                    }
                    if (StringUtils.isNotEmpty(excelRequest.getContentC())) {
                        QuestionEditItemVM questionEditItemVM = new QuestionEditItemVM();
                        questionEditItemVM.setPrefix("C");
                        questionEditItemVM.setContent(excelRequest.getContentC());
                        items.add(questionEditItemVM);
                    }
                    if (StringUtils.isNotEmpty(excelRequest.getContentD())) {
                        QuestionEditItemVM questionEditItemVM = new QuestionEditItemVM();
                        questionEditItemVM.setPrefix("D");
                        questionEditItemVM.setContent(excelRequest.getContentD());
                        items.add(questionEditItemVM);
                    }
                    if (StringUtils.isNotEmpty(excelRequest.getContentE())) {
                        QuestionEditItemVM questionEditItemVM = new QuestionEditItemVM();
                        questionEditItemVM.setPrefix("E");
                        questionEditItemVM.setContent(excelRequest.getContentE());
                        items.add(questionEditItemVM);
                    }
                    model.setItems(items);
                    RestResponse validQuestionEditRequestResult = validQuestionEditRequestVM(model);
                    if (validQuestionEditRequestResult.getCode() != SystemCode.OK.getCode()) {
                        return validQuestionEditRequestResult;
                    }

                    if (null == model.getId()) {
                        questionService.insertFullQuestion(model, 7);
                    } else {
                        questionService.updateFullQuestion(model);
                    }
                }
                return RestResponse.ok();

            } catch (IOException e) {
                return RestResponse.fail(2, e.getMessage());
            }
        } else {
            return RestResponse.fail(2, "检查文件格式是否正确！");
        }
    }

    @RequestMapping(value = "/media2", method = RequestMethod.POST)
    @ResponseBody
    public RestResponse uploadMedia(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        long attachSize = multipartFile.getSize();
        String imgName = multipartFile.getOriginalFilename();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
            userService.changePicture(getCurrentUser(), filePath);
            return RestResponse.ok(filePath);
        } catch (IOException e) {
            return RestResponse.fail(2, e.getMessage());
        }
    }


    @RequestMapping(value = "/media", method = RequestMethod.POST)
    @ResponseBody
    public RestResponse questionUploadAndMedia(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        long attachSize = multipartFile.getSize();
        String imgName = multipartFile.getOriginalFilename();
        try (InputStream inputStream = multipartFile.getInputStream()) {
            //视频上传
            //获取原文件名
            String name = multipartFile.getOriginalFilename();
            //获取文件后缀
            String subffix = name.substring(name.lastIndexOf(".") + 1, name.length());
            //控制格式
            if (subffix.equals("") || (!subffix.equals("mp4") && !subffix.equals("mov") && !subffix.equals("avi") && !subffix.equals("wmv") && !subffix.equals("m4v") && !subffix.equals("dat") && !subffix.equals("flv") && !subffix.equals("mkv"))) {
                return RestResponse.fail(2, ("视频格式不对"));
            }
            //新的文件名以日期命名
            String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            //获取项目路径到webapp
            //String filepath = request.getServletContext().getRealPath("/") + "files\\";
            //获取项目根路径并转到static/videos
            String path = "D:\\media\\image";
            File file = new File(path);
            ////文件夹不存在就创建
            if (!file.exists()) {
                file.mkdirs();
            }
            //保存文件
            try {
                multipartFile.transferTo(new File(file + "\\" + fileName + "." + subffix));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String simulationVideo = urlLocal + "/" + fileName + "." + subffix;
            return RestResponse.ok(simulationVideo);
        } catch (IOException e) {
            return RestResponse.fail(2, e.getMessage());
        }
    }


    @RequestMapping("/image")
    @ResponseBody
    public RestResponse questionUploadAndReadExcel2(HttpServletRequest request) {
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        long attachSize = multipartFile.getSize();
        String imgName = multipartFile.getOriginalFilename();
        String subffix = imgName.substring(imgName.lastIndexOf(".") + 1, imgName.length());
        String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        try (InputStream inputStream = multipartFile.getInputStream()) {
            //String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
            //userService.changePicture(getCurrentUser(), filePath);
            String path = "D:\\media\\image";
            File file = new File(path);
            ////文件夹不存在就创建
            if (!file.exists()) {
                file.mkdirs();
            }
            //保存文件
            try {
                multipartFile.transferTo(new File(file + "\\" + fileName + "." + subffix));
            } catch (IOException e) {
                e.printStackTrace();
            }
            String simulationVideo = urlLocal + "/" + fileName + "." + subffix;
            return RestResponse.ok(simulationVideo);
        } catch (IOException e) {
            return RestResponse.fail(2, e.getMessage());
        }
    }


    private RestResponse validQuestionEditRequestVM(QuestionEditRequestVM model) {
        int qType = model.getQuestionType().intValue();
        boolean requireCorrect = qType == QuestionTypeEnum.SingleChoice.getCode() || qType == QuestionTypeEnum.TrueFalse.getCode();
        if (requireCorrect) {
            if (StringUtils.isBlank(model.getCorrect())) {
                String errorMsg = ErrorUtil.parameterErrorFormat("correct", "不能为空");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }

        if (qType == QuestionTypeEnum.GapFilling.getCode()) {
            Integer fillSumScore = model.getItems().stream().mapToInt(d -> ExamUtil.scoreFromVM(d.getScore())).sum();
            Integer questionScore = ExamUtil.scoreFromVM(model.getScore());
            if (!fillSumScore.equals(questionScore)) {
                String errorMsg = ErrorUtil.parameterErrorFormat("score", "空分数和与题目总分不相等");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }
        return RestResponse.ok();
    }


}
